var redis = require("redis");
var client = redis.createClient(6379, '127.0.0.1');
var logger = require('./logger');

// redis token操作
class RedisToken {

    /**
     * 构造函数
     */
    constructor(redisClient, key = `weixin-token`) {
        this.redisClient = redisClient; // redis client实例
        this.key = key; // redis token key
        this.isGeting = false; // 是否向redis获取token中
        this.token = null;
        this.invokeCount = 0; // redis get token计数
    }

    // token保存，返回promise
    store(token) {
        this.token = token;
        return new Promise((resolve, reject) => {
            this.redisClient.set(this.key, JSON.stringify(token), (err, res) => {
                if (err) {
                    logger.error(err);
                    reject(err);
                } else {
                    logger.debug(`Store token to redis >> ${res}`);
                    resolve();
                }
            });
        });
    }

    // token获取，返回promise
    get(forceRedis = false) {
        return new Promise((resolve, reject) => {
            if (!forceRedis && this.isGeting) {
            	logger.debug(`[RedisToken] token is getting from local cache.`);
                resolve(this.token);
                return;
            }

            this.isGeting = true;
            this.redisClient.get(this.key, (err, res) => {
                this.isGeting = false;
                this.invokeCount++;
                if (err) {
                    logger.error(`[RedisToken] ${err}`);
                    reject(err);
                } else {
                    logger.debug(`[RedisToken] got token from redis >> ${res}`);
                    this.token = JSON.parse(res);
                    resolve(this.token);
                }
            });
        });
    }

    // token删除，返回promise
    del() {
        return new Promise((resolve, reject) => {
            this.redisClient.del(this.key, (err, res) => {
                if (err) {
                    logger.error(`[RedisToken] ${err}`);
                    reject(err);
                } else {
                    logger.debug(`[RedisToken] delete token from redis >> ${res}`);
                    resolve(res === 1);
                }
            });
        });
    }
}

module.exports = new RedisToken(client); // 导出单例实现